# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import ShoppingCart, OrderInfo, PayInfo
from goods.models import Product, Good
from goods.serializers import ProductSerializer, GoodParamSerializer
from utils import gen_order_no
from utils.alipay import AliPay
from shop.settings import private_key, alipay_public_key


class OrderInfoSerializer(serializers.ModelSerializer):
    goods = GoodParamSerializer(many=False)
    pay_money = serializers.FloatField(required=False)

    # 研究
    # def create(self, validated_data):

    # 可以在这里注入 金额
    def validate(self, attrs):
        return attrs

    class Meta:
        model = OrderInfo
        fields = '__all__'


class PayDetailSerializer(serializers.ModelSerializer):
    goods = OrderInfoSerializer(many=True)

    class Meta:
        model = PayInfo
        fields = '__all__'


class UpdatePayStatusSerializer(serializers.ModelSerializer):

    def get_pay_url(self, obj, title):
        alipay = AliPay(
            appid="2016101000652414",
            app_notify_url="http://139.199.123.96:8000/alipay/return/",
            app_private_key_path=private_key,
            alipay_public_key_path=alipay_public_key,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://139.199.123.96:8000/alipay/return/"
        )

        url = alipay.direct_pay(
            subject=title,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)

        return re_url

    def product_name(self, instance):
        orders = OrderInfo.objects.filter(pay=instance)
        titles = []
        for order in orders:
            for param in order.goods.params:
                titles.append(param['value'])
        return '-'.join(titles)

    def update(self, instance, validated_data):
        title = self.product_name(instance)
        # 判断时间是否大于两个小时
        if instance.pay_url:
            return instance
        instance.pay_url = self.get_pay_url(instance, title)
        instance.save()
        return instance

    class Meta:
        model = PayInfo
        fields = ['pay_url', 'pay_type']


class OncePayInfoSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    add_time = serializers.DateTimeField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    status = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_sn = serializers.CharField(read_only=True)
    order_mount = serializers.FloatField(read_only=True)
    coupon = serializers.IntegerField(required=False, read_only=True)
    pay_url = serializers.CharField(read_only=True)
    is_delete = serializers.IntegerField(read_only=True)
    goods = OrderInfoSerializer(many=True)

    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2016101000652414",
            app_notify_url="http://139.199.123.96:8000/alipay/return/",
            app_private_key_path=private_key,
            alipay_public_key_path=alipay_public_key,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://139.199.123.96:8000/alipay/return/"
        )

        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)

        return re_url

    # 序列化时生成订单号
    def validate(self, attrs):
        attrs['order_mount'] = 0
        attrs['order_sn'] = gen_order_no(self.context['request'])
        return attrs

    class Meta:
        model = PayInfo
        fields = '__all__'


class PayInfoSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    add_time = serializers.DateTimeField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    status = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_sn = serializers.CharField(read_only=True)
    order_mount = serializers.FloatField(read_only=True)
    coupon = serializers.IntegerField(required=False, read_only=True)
    pay_url = serializers.CharField(read_only=True)
    # pay_title = serializers.CharField(read_only=True)
    is_delete = serializers.IntegerField(read_only=True)
    goods = OrderInfoSerializer(many=True, read_only=True)

    # alipay_url = serializers.SerializerMethodField(read_only=True)

    # 在校验的时候进行赋值计算
    # order_mount = serializers.SerializerMethodField(read_only=True, required=False)
    #
    # def get_order_mount(self, obj):
    #     shop_cart = ShoppingCart.objects.filter(user=obj.user).filter(is_select=True)
    #     for shop in shop_cart:
    #         print(shop.nums)
    #     return 100

    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2016101000652414",
            app_notify_url="http://139.199.123.96:8000/alipay/return/",
            app_private_key_path=private_key,
            alipay_public_key_path=alipay_public_key,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://139.199.123.96:8000/alipay/return/"
        )

        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)

        return re_url

    def get_total_price(self, request):
        shop_cart = ShoppingCart.objects.filter(user=request.user).filter(is_select=True)
        total = 0
        for shop in shop_cart:
            nums = shop.nums
            price = shop.goods.sold_price
            total += nums * price

        return total

    # 序列化时生成订单号
    def validate(self, attrs):
        attrs['order_mount'] = self.get_total_price(self.context['request'])
        attrs['order_sn'] = gen_order_no(self.context['request'])
        return attrs

    class Meta:
        model = PayInfo
        fields = '__all__'


class GoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = Good
        fields = "__all__"


class ShoppingDetailSerializer(serializers.ModelSerializer):
    goods = GoodSerializer(many=False, read_only=True)

    class Meta:
        model = ShoppingCart
        fields = ['goods', 'nums', 'is_select']


class ShoppingCartSerializer(serializers.Serializer):
    # 使用 Serializer 需要自定义 不能 Meta
    # 搜藏的是商品 不是 产品
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    goods = serializers.PrimaryKeyRelatedField(queryset=Good.objects.all(), required=True)
    is_select = serializers.BooleanField(required=False)
    nums = serializers.IntegerField(min_value=1, error_messages={'min_value': '数量必须大于1'}, required=True)

    # post 进行修改操作
    def create(self, validated_data):
        user = self.context['request'].user
        nums = validated_data['nums']
        goods = validated_data['goods']
        is_exist = ShoppingCart.objects.filter(user=user, goods=goods)
        if is_exist:
            cart_object = is_exist[0]
            cart_object.nums += nums
            cart_object.save()
        else:
            cart_object = ShoppingCart.objects.create(**validated_data)

        return cart_object

    # put 进行更新操作  这里支持 patch
    # patch和put的数据肯定存在
    def update(self, instance, validated_data):
        # print(validated_data)
        # try:
        #     instance.nums = validated_data['nums']
        #     instance.is_select = validated_data['is_select']
        # except:
        #     instance.is_select = validated_data['is_select']
        # validated_data.pop('goods')
        # print(instance)
        for key in validated_data.keys():
            setattr(instance, key, validated_data[key])
            # print(key, validated_data[key])
            # print(instance.key)
            # instance.key = validated_data[key]
            instance.save()

        # instance.nums = 111
        # instance.save()
        return instance

    # 如果不是 list  也可以不加下面的
    # class Meta:
    #     model = ShoppingCart
    #     fields = ['goods', 'nums', 'is_select']
